const CartKey = 'yncarts'

export const saveCartData = (storeId, cartData) => {
  let cartStorage = window.localStorage.getItem(CartKey);
  if (cartStorage) {
    cartStorage = JSON.parse(cartStorage);
    cartStorage[storeId] = cartData;
  } else {
    cartStorage = {
      [storeId]: cartData
    }
  }
  if (cartStorage) window.localStorage.setItem(CartKey, JSON.stringify(cartStorage));
}

export const readCartData = (storeId) => {
  let cartStorage = window.localStorage.getItem(CartKey);
  let result = {};
  if(cartStorage) {
    cartStorage = JSON.parse(cartStorage);
    result = cartStorage[storeId] ? cartStorage[storeId] : {};
  }
  return result;
}

export const clearCartData = (storeId) => {
  if (storeId) {
    let cartStorage = window.localStorage.getItem(CartKey);
    if (cartStorage) {
      cartStorage = JSON.parse(cartStorage);
      delete cartStorage[storeId]
      window.localStorage.setItem(CartKey, JSON.stringify(cartStorage));
    }
  } else {
    window.localStorage.removeItem(CartKey);
  }
}